/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package supermarket;

import ext_model.CreditCardAuthority;
import ext_model.ExternalBank;
import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;

import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import model.Customer;
import static supermarket.SuperMarket.em2;



/**
 *
 * @author root
 */
public class Authority {
    
    
    
    
    public Timestamp accessAuth(Customer customer) throws InterruptedException{
    
     
    
    
   
        System.out.println("Grant access for " + customer.getFirstName()+" "+customer.getLastName());
        
        TimeUnit.SECONDS.sleep(10);
        
     
       
       //sleep(rand.nextInt(10000));
       
    try
    {
        
           java.util.Date date= new java.util.Date();
       //βρίσκω την πιστωτική με τον αριθμό της από την εξωτερική βάση
       TypedQuery<CreditCardAuthority> q = em2.createNamedQuery("CreditCardAuthority.findByNumber", CreditCardAuthority.class);
       q.setParameter("number", customer.getCreditCard());
       CreditCardAuthority extcustomer = q.getSingleResult();
           
       //βρίσκω την τράπεζα με το όνομά της από την εξωτερική βάση
       TypedQuery<ExternalBank> q1 = em2.createNamedQuery("ExternalBank.findByName", ExternalBank.class);
       q1.setParameter("name", customer.getBank());
       ExternalBank extbank = q1.getSingleResult();
      
            
        if (extcustomer.getNumber().equals(customer.getCreditCard())&&
               extcustomer.getOwnerName().equals(customer.getCcOwner())&&
               extcustomer.getCvv().equals(customer.getCvv())&&
               extbank.getName().equals(customer.getBank())
               ){
               
            
            
               
                return  new Timestamp(date.getTime());
           }
       
    }
    
    catch(NoResultException e)
    {
        System.out.println("Cannot find credit card for "+customer.getFirstName()+" "+ customer.getLastName());
        
    }
       
        return null;
          
                
    }
    
    
    
}
